//
//  SKFirstVController.m
//  SKaURobot
//
//  Created by cdong on 16/2/19.
//  Copyright © 2016年 cdong. All rights reserved.
//

#import "SKFirstVController.h"
#import "SKFirstView.h"
#import "THCircularProgressView.h"
#import "AFHTTPSessionManager.h"
#import "SKRegisterVController.h"
#import "connectRobotWifiVController.h"
#import "isConnectNet.h"
#import "annularView.h"
#import "growthPhotosVController.h"

@interface SKFirstVController ()

@property (nonatomic ,strong)SKFirstView *firstView;
@property (nonatomic ,strong)annularView *annularV;

@end

@implementation SKFirstVController

- (void)loadView{
    self.firstView = [[SKFirstView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.view = self.firstView;
}

// 改变状态栏的颜色
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

// 返回
- (void)backBtnAction:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    [self.firstView.operationBtn addTarget:self action:@selector(operationBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)viewWillAppear:(BOOL)animated{
    
    if (!isConnectionAvailable()) {
        [self failConnectUpdateUI];
    }else{
        if (self.updateUIFlag) {
            [self connectOKUpdateUI];
            self.updateUIFlag = NO;
            return;
        }
        [self loginAgainJudge];
    }
}

// 连接／视频通讯按钮
- (void)operationBtnAction:(UIButton *)sender{
    connectRobotWifiVController *connectVC = [[connectRobotWifiVController  alloc]init];
    [self.navigationController pushViewController:connectVC animated:YES];
}
// 没有网络的情况下
- (void)failConnectUpdateUI{

    if (self.annularV) {
        [self.annularV removeFromSuperview];
    }
    
    self.firstView.robotImageV.image = [UIImage imageNamed:@"pic_rabbit_a"];

    if (self.firstView.robotStateImageV) {
        [self.firstView.robotStateImageV removeFromSuperview];
    }
    
    if (self.firstView.robotStateL) {
        [self.firstView.robotStateL removeFromSuperview];
    }
    self.firstView.robotStateL = [[UILabel alloc]initWithFrame:CGRectMake((self.firstView.frame.size.width - 266*matchW)/2 + 10*matchW, CGRectGetMaxY(self.firstView.robotNameL.frame), 266*matchW, 21*matchH)];
    self.firstView.robotStateL.text = @"[未连接，请尽快将手机与机器人连接！]";
    self.firstView.robotStateL.font = [UIFont systemFontOfSize:14*matchW];
    self.firstView.robotStateL.textAlignment = NSTextAlignmentCenter;
    self.firstView.robotStateL.textColor = [RGBColorEncapsulation colorWithRGB:0x0ac8c6 alpha:1];
    [self.firstView addSubview:self.firstView.robotStateL];
    
    [self.firstView.operationBtn setTitle:@"连接" forState:UIControlStateNormal];
    [self.firstView.operationBtn setTitleColor:[RGBColorEncapsulation colorWithRGB:0xffffff alpha:1] forState:UIControlStateNormal];
    self.firstView.operationBtn.titleLabel.font = [UIFont systemFontOfSize:20];
    [self.firstView.operationBtn setBackgroundImage:[UIImage imageNamed:@"bg_connect"] forState:UIControlStateNormal];
    
    if (self.firstView.btn_btnView) {
        [self.firstView.btn_btnView removeFromSuperview];
    }
    if (self.firstView.btn_btnViewSetUp) {
        [self.firstView.btn_btnViewSetUp removeFromSuperview];
    }
}

// 用户连接机器人成功更新UI
- (void)connectOKUpdateUI{
    
    CGFloat radius = floor(310*matchW/2);
    
    self.firstView.robotImageV.image = [UIImage imageNamed:@"pic_rabbit"];
    
    self.annularV = [[annularView alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2 - radius, 88*matchH - 21*matchH, radius*2, radius*2)];
    self.annularV.endF = 0.6;
    self.annularV.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.annularV];

    if (self.firstView.robotStateL) {
        [self.firstView.robotStateL removeFromSuperview];
    }
    self.firstView.robotStateL = [[UILabel alloc]initWithFrame:CGRectMake((self.view.frame.size.width - 57*matchW)/2 + 10*matchW, CGRectGetMaxY(self.firstView.robotNameL.frame), 57*matchW, 21*matchH)];
    self.firstView.robotStateL.text = @"";
    self.firstView.robotStateL.text = @"[空闲中]";
    self.firstView.robotStateL.font = [UIFont systemFontOfSize:14*matchW];
    self.firstView.robotStateL.textAlignment = NSTextAlignmentCenter;
    self.firstView.robotStateL.textColor = [RGBColorEncapsulation colorWithRGB:0x0ac8c6 alpha:1];
    [self.view addSubview:self.firstView.robotStateL];
    
    self.firstView.robotStateImageV = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.firstView.robotStateL.frame) - 22 *matchW, CGRectGetMinY(self.firstView.robotStateL.frame), 21*matchW, CGRectGetHeight(self.firstView.robotStateL.frame))];
    self.firstView.robotStateImageV.image = [UIImage imageNamed:@"status_free"];
    [self.view addSubview:self.firstView.robotStateImageV];
    
    [self.firstView.operationBtn setTitle:@"" forState:UIControlStateNormal];
    [self.firstView.operationBtn setBackgroundImage:[UIImage imageNamed:@"gameboy"] forState:UIControlStateNormal];
    
    self.firstView.btn_btnView = [[SKBtn_btnEncapsulation alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.firstView.operationBtn.frame) - 52*matchW - 50*matchW, CGRectGetMinY(self.firstView.operationBtn.frame) + 12*matchH, 52*matchW, 48*matchH) imageName:@"icon_growth" title:@"成长相册"];
    [self.firstView.btn_btnView.imageBtn addTarget:self action:@selector(growthBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.firstView.btn_btnView.titleBtn addTarget:self action:@selector(growthBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.firstView.btn_btnView];
    
    self.firstView.btn_btnViewSetUp = [[SKBtn_btnEncapsulation alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.firstView.operationBtn.frame) + 50*matchW , CGRectGetMinY(self.firstView.operationBtn.frame) + 12*matchH, 52*matchW, 48*matchH) imageName:@"icon_set" title:@"设置"];
    [self.view addSubview:self.firstView.btn_btnViewSetUp];
}

// 成长相册
- (void)growthBtnAction:(UIButton *)sender{
    growthPhotosVController *growthVC = [[growthPhotosVController alloc]init];
    [self.navigationController pushViewController:growthVC animated:YES];
}

int codeRRF = 0;

// 之前登录过再次判断密码帐号正不正确
- (void)loginAgainJudge{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *userName = [userDefaults objectForKey:@"userName"];
    NSString *pwd = [userDefaults objectForKey:@"password"];
    NSString *urlStr =  [NSString stringWithFormat:@"http://api.au-smart.cn/index.php?act=login&userName=%@&password=%@",userName,pwd];
    NSString *utf = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:utf parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        NSNumber *error = [responseObject objectForKey:@"error"];
        NSNumber *uid = [responseObject objectForKey:@"uid"];
        NSString *sesskey = [responseObject objectForKey:@"sesskey"];
        NSNumber *errorCode = [responseObject objectForKey:@"errorCode"];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:uid forKey:@"uid"];
        [defaults setObject:sesskey forKey:@"sesskey"];
        if (error.integerValue == 0) {
            NSUserDefaults *userdefaut = [NSUserDefaults standardUserDefaults];
            if (errorCode.integerValue == 1031) { // 老用户未绑定手机号跳转
                codeRRF = 103;
                [userdefaut setInteger:codeRRF forKey:@"registerOrGetCode"];
                SKRegisterVController *bandPhoneV = [[SKRegisterVController alloc]init];
                [self.navigationController pushViewController:bandPhoneV animated:YES];
            }else{
                [self connectOKUpdateUI];
            }

        }else{ // 如果已经登录过用户再次进入app，直接进首页，后台登录，登录失败，进入未连接机器人UI,按需求不进行错误提示
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"fail~~~");
    }];

}
 
// 提示弹框
- (void)alertReminderMessage:(NSString *)message
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
